import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;

/**
 * Created with IntelliJ IDEA.
 * User: Thoughtworker
 * Date: 8/22/13
 * Time: 7:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class TennisGame {

    private CalculateScore calculateScore = new CalculateScore();
    private int firstPlayerPoints;
    private int secondPlayerPoints;
    private BufferedReader bufferedReader;
    private PrintStream printStream;

    public TennisGame(BufferedReader bufferedReader, PrintStream printStream) {
        this.bufferedReader = bufferedReader;
        firstPlayerPoints = 0;
        secondPlayerPoints = 0;
        this.printStream = printStream;
    }

    public String readUserInput() throws IOException {
        String input = bufferedReader.readLine();
        return input;
    }

    public void playerScores(String player) throws IOException {
        if(player.equals("1")){
            firstPlayerScores();
        } else if(player.equals("2")){
            secondPlayerScores();
        }else{
            printStream.println("Please enter a valid player");
            run();
        }

    }

    public void run() throws IOException {
        while(!hasWinner()){
            printStream.println("Enter the player that wins the point:");
            playerScores(readUserInput());
            System.out.println(getScore(firstPlayerPoints,secondPlayerPoints));
        }
    }

    public String getScore(int firstPlayerPoints, int secondPlayerPoints) {
        return calculateScore.getScore(firstPlayerPoints, secondPlayerPoints);
    }

    public void firstPlayerScores() {
        firstPlayerPoints++;
    }

    public void secondPlayerScores() {
        secondPlayerPoints++;
    }

    public boolean hasWinner() {

        if (secondPlayerPoints >= 4 && secondPlayerPoints >= firstPlayerPoints + 2)
            return true;
        if (firstPlayerPoints >= 4 && firstPlayerPoints >= secondPlayerPoints + 2)
            return true;
        return false;

    }

    public int getFirstPlayerPoints() {
        return firstPlayerPoints;
    }

    public int getSecondPlayerPoints() {
        return secondPlayerPoints;
    }



}
